package com.visualize.demo.service;

import com.visualize.demo.model.JsonResponse;
import com.visualize.demo.model.Project;
import com.visualize.demo.repository.ProjectRepository;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AccountService {

    private final ProjectRepository projectRepository;
    private final EntityManager em;

    private enum UserType {
        FAIL,
        HUMAN,
        ROBOT,
        TOTAL
    }

    public AccountService(ProjectRepository projectRepository, EntityManager em) {
        this.projectRepository = projectRepository;
        this.em = em;
    }

    public JsonResponse showProjectList() {
        List<Project> projectsList = projectRepository.getProjectList();
        Map<String, List<Project>> content = new HashMap<>();
        content.put("list", projectsList);
        return new JsonResponse(200, content);
    }

    public JsonResponse showPercent(Integer id) {
        Project project = projectRepository.getProjectById(id);
        Map<String, BigInteger> content = new HashMap<>();
        content.put("humanCount", this.getUserCount(UserType.HUMAN, project.getAccount_table()));
        content.put("robotCount", this.getUserCount(UserType.ROBOT, project.getAccount_table()));
        content.put("failCount", this.getUserCount(UserType.FAIL, project.getAccount_table()));
        content.put("totalCount", this.getUserCount(UserType.TOTAL, project.getAccount_table()));
        return new JsonResponse(200, content);
    }

    /**
     * Get User Count From :accountTable
     *
     * @param type UserType
     * @param accountTable TableName
     * @return BigInteger
     */
    private BigInteger getUserCount(UserType type, String accountTable) {
        String s;
        switch (type) {
            case FAIL:
                s = "select count(1) as num From %s WHERE score = 0;";
                break;
            case HUMAN:
                s = "select count(1) as num From %s WHERE score < 3 and score <> 0;";
                break;
            case ROBOT:
                s = "select count(1) as num From %s WHERE score >= 3;";
                break;
            case TOTAL:
                s = "select count(1) as num From %s;";
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
        String sql = String.format(s, accountTable);
        System.out.println(sql);
        List list = em.createNativeQuery(sql).getResultList();
        return (BigInteger) list.get(0);
    }
}
